<template>
  <div class="profile-container">
    <el-row :gutter="20">
      <!-- 用户信息卡片 -->
      <el-col :xs="24" :lg="8">
        <el-card class="user-card">
          <div class="user-info">
            <el-avatar :size="100" :src="userAvatar" class="user-avatar">
              <el-icon><User /></el-icon>
            </el-avatar>
            
            <div class="user-details">
              <h2>{{ authStore.userInfo?.username }}</h2>
              <p class="user-email">{{ authStore.userInfo?.email }}</p>
              <el-tag :type="userSourceType" class="user-source">
                {{ userSourceText }}
              </el-tag>
            </div>
            
            <div class="user-actions">
              <el-button type="primary" @click="showEditDialog">
                <el-icon><Edit /></el-icon>
                编辑资料
              </el-button>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <!-- 详细信息 -->
      <el-col :xs="24" :lg="16">
        <el-card>
          <template #header>
            <span>详细信息</span>
          </template>
          
          <el-descriptions :column="2" border>
            <el-descriptions-item label="用户ID">
              {{ authStore.userInfo?.id }}
            </el-descriptions-item>
            <el-descriptions-item label="用户名">
              {{ authStore.userInfo?.username }}
            </el-descriptions-item>
            <el-descriptions-item label="邮箱">
              {{ authStore.userInfo?.email }}
            </el-descriptions-item>
            <el-descriptions-item label="注册来源">
              {{ userSourceText }}
            </el-descriptions-item>
            <el-descriptions-item label="注册时间">
              {{ authStore.userInfo?.createdAt || '未知' }}
            </el-descriptions-item>
            <el-descriptions-item label="最后登录">
              {{ lastLoginTime }}
            </el-descriptions-item>
          </el-descriptions>
        </el-card>
        
        <!-- 安全设置 -->
        <el-card style="margin-top: 20px;">
          <template #header>
            <span>安全设置</span>
          </template>
          
          <div class="security-settings">
            <div class="security-item">
              <div class="security-info">
                <h4>密码</h4>
                <p>定期更改密码以确保账户安全</p>
              </div>
              <el-button type="primary" size="small" @click="showChangePasswordDialog">
                修改密码
              </el-button>
            </div>
            
            <div class="security-item">
              <div class="security-info">
                <h4>两步验证</h4>
                <p>为您的账户添加额外的安全保护</p>
              </div>
              <el-button type="success" size="small" @click="showTwoFactorDialog">
                启用
              </el-button>
            </div>
            
            <div class="security-item">
              <div class="security-info">
                <h4>登录设备</h4>
                <p>管理您的登录设备</p>
              </div>
              <el-button type="info" size="small" @click="showDevicesDialog">
                查看设备
              </el-button>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 编辑资料对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑资料"
      width="500px"
      @close="resetEditForm"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editRules"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username" />
        </el-form-item>
        
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email" />
        </el-form-item>
        
        <el-form-item label="头像">
          <el-upload
            class="avatar-uploader"
            action="#"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="editForm.avatar" :src="editForm.avatar" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleEditSubmit" :loading="editLoading">
          保存
        </el-button>
      </template>
    </el-dialog>
    
    <!-- 修改密码对话框 -->
    <el-dialog
      v-model="passwordDialogVisible"
      title="修改密码"
      width="400px"
      @close="resetPasswordForm"
    >
      <el-form
        ref="passwordFormRef"
        :model="passwordForm"
        :rules="passwordRules"
        label-width="100px"
      >
        <el-form-item label="当前密码" prop="currentPassword">
          <el-input
            v-model="passwordForm.currentPassword"
            type="password"
            show-password
          />
        </el-form-item>
        
        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="passwordForm.newPassword"
            type="password"
            show-password
          />
        </el-form-item>
        
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="passwordForm.confirmPassword"
            type="password"
            show-password
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="passwordDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handlePasswordSubmit" :loading="passwordLoading">
          修改
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { User, Edit, Plus } from '@element-plus/icons-vue'
import { useAuthStore } from '@/stores/auth'

const authStore = useAuthStore()

// 对话框状态
const editDialogVisible = ref(false)
const passwordDialogVisible = ref(false)
const twoFactorDialogVisible = ref(false)
const devicesDialogVisible = ref(false)

// 加载状态
const editLoading = ref(false)
const passwordLoading = ref(false)

// 表单引用
const editFormRef = ref<FormInstance>()
const passwordFormRef = ref<FormInstance>()

// 编辑表单
const editForm = reactive({
  username: '',
  email: '',
  avatar: ''
})

// 密码表单
const passwordForm = reactive({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 用户头像
const userAvatar = computed(() => {
  return authStore.userInfo?.avatar || editForm.avatar || ''
})

// 用户来源类型
const userSourceType = computed(() => {
  return authStore.userInfo?.source === 'wechat' ? 'success' : 'primary'
})

// 用户来源文本
const userSourceText = computed(() => {
  return authStore.userInfo?.source === 'wechat' ? '微信登录' : '账号注册'
})

// 最后登录时间
const lastLoginTime = computed(() => {
  return new Date().toLocaleString()
})

// 编辑表单验证规则
const editRules: FormRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, message: '用户名长度不能少于3位', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ]
}

// 密码表单验证规则
const passwordRules: FormRules = {
  currentPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 显示编辑对话框
const showEditDialog = () => {
  editForm.username = authStore.userInfo?.username || ''
  editForm.email = authStore.userInfo?.email || ''
  editForm.avatar = authStore.userInfo?.avatar || ''
  editDialogVisible.value = true
}

// 重置编辑表单
const resetEditForm = () => {
  Object.assign(editForm, {
    username: '',
    email: '',
    avatar: ''
  })
  editFormRef.value?.resetFields()
}

// 处理编辑提交
const handleEditSubmit = async () => {
  if (!editFormRef.value) return
  
  try {
    await editFormRef.value.validate()
    editLoading.value = true
    
    // 这里应该调用更新用户信息的 API
    // 暂时模拟成功
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    ElMessage.success('资料更新成功')
    editDialogVisible.value = false
  } catch (error) {
    console.error('更新资料失败:', error)
  } finally {
    editLoading.value = false
  }
}

// 显示修改密码对话框
const showChangePasswordDialog = () => {
  passwordDialogVisible.value = true
}

// 重置密码表单
const resetPasswordForm = () => {
  Object.assign(passwordForm, {
    currentPassword: '',
    newPassword: '',
    confirmPassword: ''
  })
  passwordFormRef.value?.resetFields()
}

// 处理密码修改提交
const handlePasswordSubmit = async () => {
  if (!passwordFormRef.value) return
  
  try {
    await passwordFormRef.value.validate()
    passwordLoading.value = true
    
    // 这里应该调用修改密码的 API
    // 暂时模拟成功
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    ElMessage.success('密码修改成功')
    passwordDialogVisible.value = false
  } catch (error) {
    console.error('修改密码失败:', error)
  } finally {
    passwordLoading.value = false
  }
}

// 头像上传前处理
const beforeAvatarUpload = (file: File) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('头像图片只能是 JPG/PNG 格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('头像图片大小不能超过 2MB!')
    return false
  }
  
  // 这里应该上传到服务器
  const reader = new FileReader()
  reader.onload = (e) => {
    editForm.avatar = e.target?.result as string
  }
  reader.readAsDataURL(file)
  
  return false
}

// 显示两步验证对话框
const showTwoFactorDialog = () => {
  ElMessage.info('两步验证功能开发中...')
}

// 显示设备管理对话框
const showDevicesDialog = () => {
  ElMessage.info('设备管理功能开发中...')
}
</script>

<style scoped>
.profile-container {
  max-width: 1200px;
  margin: 0 auto;
}

.user-card {
  margin-bottom: 20px;
}

.user-info {
  text-align: center;
}

.user-avatar {
  margin-bottom: 20px;
}

.user-details h2 {
  margin: 0 0 10px 0;
  font-size: 24px;
  color: #333;
}

.user-email {
  margin: 0 0 15px 0;
  color: #666;
  font-size: 14px;
}

.user-source {
  margin-bottom: 20px;
}

.user-actions {
  margin-top: 20px;
}

.security-settings {
  space-y: 20px;
}

.security-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 0;
  border-bottom: 1px solid #f0f0f0;
}

.security-item:last-child {
  border-bottom: none;
}

.security-info h4 {
  margin: 0 0 5px 0;
  font-size: 16px;
  color: #333;
}

.security-info p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.avatar-uploader {
  text-align: center;
}

.avatar-uploader .avatar {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  object-fit: cover;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
  border: 1px dashed #d9d9d9;
  border-radius: 50%;
}

:deep(.el-descriptions__label) {
  font-weight: 600;
}

:deep(.el-descriptions__content) {
  color: #666;
}
</style>
